package com.base.lib.base

import android.R
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import butterknife.ButterKnife
import com.base.lib.utils.Constant
import com.base.lib.utils.eventbus.EventBusMessage
import com.base.lib.view.SnackbarUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author harisucici
 * @date 07.03
 */
abstract class BaseFragment<V, T : BasePresenter<V>?> : Fragment(), BaseView {
    @JvmField
    var mContext: Context? = null
    @JvmField
    var mActivity: BaseActivity<*, *>? = null
    var isShow = false
    var isPrepared = false
    var mCamareFile: File? = null
    //输出数据展示
    var mGattServices: List<BluetoothGattService> = ArrayList()
    //设备特征值集合
    var mGattCharacteristics: List<List<BluetoothGattCharacteristic>> = ArrayList()
    @JvmField
    protected var mPresenter: T? = null
    //    protected ProgressDialog progressDialog;
    protected lateinit var rootView: View
    private var progressDialog: ProgressDialog? = null
    //设备信息
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (rootView == null) {
            mPresenter = initPresenter()
            if (progressDialog == null) {
                progressDialog = ProgressDialog()
            }
            //            progressDialog = new ProgressDialog();
            mContext = context
            mActivity = activity as BaseActivity<*, *>?
            rootView = inflater.inflate(setViewId(), container, false)
            isPrepared = true
            ButterKnife.bind(this, rootView)
            EventBus.getDefault().register(this)
            initView()
            initData()
        }
        val parent = rootView!!.parent as ViewGroup
        parent?.removeView(rootView)
        return rootView
    }

    override fun setUserVisibleHint(isShowToUser: Boolean) {
        super.setUserVisibleHint(isShowToUser)
        isShow = userVisibleHint
        if (!isPrepared || !isShow) {
            return
        }
        if (isPrepared) {
            if (userVisibleHint) {
                isShow = true
                if (!EventBus.getDefault().isRegistered(this)) {
                    EventBus.getDefault().register(this)
                }
                doOnVisible()
            } else {
                isShow = false
                doOnInvisible()
            }
        }
    }
    override fun onResume() {
        super.onResume()
        mPresenter?.attachView(this as V)
        doOnResume()
        Log.i("BaseFragment_Me", "onResume")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mPresenter?.detachView()
        doOnDestroy()
        EventBus.getDefault().unregister(this)
        Log.i("BaseFragment_Me", "onDestroyView")
    }

    abstract fun initPresenter(): T
    protected abstract fun setViewId(): Int
    protected abstract fun initView()
    protected abstract fun initData()
    protected abstract fun doOnDestroy()
    protected abstract fun doOnResume()
    protected abstract fun doOnVisible()
    protected abstract fun doOnInvisible()
    protected abstract fun doOnSaveInstanceState(savedInstanceState: Bundle?)
    override fun onSaveInstanceState(savedInstanceState: Bundle) {
        super.onSaveInstanceState(savedInstanceState)
        doOnSaveInstanceState(savedInstanceState)
    }

    //    @Override
//    public void showLoadingDialog() {
//        progressDialog.show(mActivity.getSupportFragmentManager(),"1");
//        showLoadingDialog(null, null);
//    }
    override fun showLoadingDialog() { //        showLoadingDialog(null, "请等待");
        if (progressDialog!!.tag == null) {
            progressDialog!!.show(mActivity!!.getSupportFragmentManager(), "progress")
        }
    }

    //    public void showLoadingDialog(String title, String message) {
//        if (mProgressDialog == null) {
//            mProgressDialog = new ProgressDialog(getActivity());
//            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        }
//
//        if (title == null) {
//            title = "";
//        }
//        if (message == null) {
//            message = "";
//        }
//
//        mProgressDialog.setTitle(title);
//        mProgressDialog.setMessage(message);
//        mProgressDialog.show();
//    }
//    @Override
//    public void dismissLoadingDialog() {
//        if (mProgressDialog != null && mProgressDialog.isShowing()) {
//            mProgressDialog.dismiss();
//        }
//        progressDialog.dismiss();
//    }
    override fun dismissLoadingDialog() { //        if (mProgressDialog != null && mProgressDialog.isShowing()) {
//            mProgressDialog.dismiss();
//        }
        if (progressDialog != null) {
            progressDialog!!.dismiss()
        }
    }

    @Subscribe
    fun onEventMainThread(eventBusMessage: EventBusMessage) {
        Log.i(EventBus.TAG, "onEventMainThread: $eventBusMessage")
    }

    override fun getActivityContext(): Context? {
        return context
    }

    fun showShortToast(message: String) {
        val imm = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(activity!!.window.decorView.windowToken, 0)
        SnackbarUtil.showBarShortTime(activity!!.findViewById(R.id.content), message, SnackbarUtil.INFO)
    }

    fun showShortToast(message: String, type: Int) {
        val imm = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(activity!!.window.decorView.windowToken, 0)
        SnackbarUtil.showBarShortTime(activity!!.findViewById(R.id.content), message, type)
    }

    protected fun showShortToast(message: String, listener: View.OnClickListener, info: String?) {
        val imm = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm?.hideSoftInputFromWindow(activity!!.window.decorView.windowToken, 0)
        SnackbarUtil.showBarShortTime(activity!!.findViewById(R.id.content), message, SnackbarUtil.INFO, info, listener)
    }

    fun chooseLocImage() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        startActivityForResult(intent, Constant.REQUEST_CODE_IMAGE)
    }

    fun chooseLocCamera(path: String) {
        val dir = File(Environment.getExternalStorageDirectory(), "Jh3502/$path")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val df = SimpleDateFormat("yyyyMMddHHmmss") //设置日期格式在android中，创建文件时，文件名中不能包含“：”冒号
        val filename = df.format(Date())
        mCamareFile = File(dir, "$filename.png")
        if (!mCamareFile!!.exists()) {
            try {
                mCamareFile!!.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        selectImageFromCamera(Constant.REQUEST_CODE_CAMERA, mCamareFile)
    }

    fun selectImageFromCamera(requestCode: Int, saveImage: File?) {
        var saveImage = saveImage
        if (saveImage == null) {
            Log.i(EventBus.TAG, "Image file parameter is null.")
            saveImage = File(Environment.getExternalStorageDirectory(), System.currentTimeMillis().toString() + ".png")
        }
        val currentapiVersion = Build.VERSION.SDK_INT
        Log.i(EventBus.TAG, "---currentapiVersion===$currentapiVersion")
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (currentapiVersion < Build.VERSION_CODES.N) {
            intent.action = MediaStore.ACTION_IMAGE_CAPTURE
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(saveImage))
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1)
        } else {
            if (saveImage.exists()) {
                try {
                    saveImage.createNewFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            val contentValues = ContentValues()
            contentValues.put(MediaStore.Images.Media.DATA, saveImage.absolutePath)
            val uri = mContext!!.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        }
        startActivityForResult(intent, requestCode)
    }
}